package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 统计指定时间内的营业额数据
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //获取日期列表
        List<LocalDate> dateList = getDateList(begin, end);

        //存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询date日期对应的营业额数据, 营业额: 状态为 '已完成' 的订单金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);    //当天0点0分0秒
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);  //当天23点59分59.999999999秒

            //从数据库获取营业额
            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);

            //如果turnover为null, 将其赋值为零
            turnover = turnover == null ? 0.0 : turnover;

            //将营业额添加到集合
            turnoverList.add(turnover);
        }

        //封装返回结果
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))  //将集合转化为字符串
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }


    /**
     * 统计指定时间内的用户数据
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //获取日期列表
        List<LocalDate> dateList = getDateList(begin, end);

        //当前集合用于存放每天日期的新用户量
        List<Integer> newUserList = new ArrayList<>();
        //当前集合用于存放每天日期的总用户量
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //获取当天时间范围
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//当天0点0分0秒
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//当天23点59分59.999999999秒

            Map map = new HashMap<>();
            map.put("end", endTime);
            //从数据库获取总用户数
            Integer totalUser = userMapper.countByMap(map);
            //添加用户总数到总用户数列表
            totalUserList.add(totalUser);

            map.put("begin", beginTime);
            //从数据库获取新用户数
            Integer newUser = userMapper.countByMap(map);
            //添加新用户数到新用户数列表
            newUserList.add(newUser);

        }

        //封装结果数据
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }


    /**
     * 统计指定时间内的订单数据
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //获取日期列表
        List<LocalDate> dateList = getDateList(begin, end);

        //每日订单总数列表
        List<Integer> orderCountList = new ArrayList<>();
        //每日有效订单数列表
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            //获取当天时间范围
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//当天0点0分0秒
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//当天23点59分59.999999999秒

            //获取每日订单数
            Integer orderDayCount = getOrdersCount(beginTime, endTime, null);
            //添加到每日订单数列表
            orderCountList.add(orderDayCount);

            //获取每日有效订单数
            Integer validDayOrderCount = getOrdersCount(beginTime, endTime, Orders.COMPLETED);
            //添加到每日有效订单数列表
            validOrderCountList.add(validDayOrderCount);
        }

        //计算时间区间内的订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        //计算时间区间内的有效订单总数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            //计算订单完成率
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        //封装返回结果
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }


    /**
     * 统计指定时间区间内的销量排名top10数据
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);//当天0点0分0秒
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MIN);//当天23点59分59.999999999秒
        //获取订单销量前十的数据
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        //提取数据中的各属性并封装到List集合
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        //封装返回结果
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 获取日期列表
     */
    public List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        //把起始日期添加到日期列表
        dateList.add(begin);
        //依次添加范围内的日期到日期列表
        while (!begin.equals(end)) {
            //开始日期加一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        return dateList;
    }

    /**
     * 根据动态条件获取订单数据
     */
    private Integer getOrdersCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);

        return orderMapper.countByMap(map);
    }

}
